/**
 * 数据库管理系统前端脚本
 */

// 全局变量定义在main-init.js中，这里不再重复定义
// 此文件中主要包含内容加载和处理函数

/**
 * 加载内容区域
 * @param {string} target - 目标内容类型
 */
function loadContent(target) {
    // 记录当前表
    currentDbTable = target;
    
    // 清理之前模块的资源
    cleanupResources();
    
    // 根据目标加载不同内容
    switch (target) {
        case 'competing_aircraft':
            loadCompetingAircraft();
            break;
        case 'fmeafmes':
            loadFMEAFMES();
            break;
        case 'operation':
            loadOperation();
            break;
        case 'dfcmdata_tables':
            // 确保loadDfcmTables函数存在并可用
            if (typeof window.loadDfcmTables === 'function') {
                window.loadDfcmTables();
            } else {
                showMessage('DFCM数据库表格模块未正确加载', 'error');
                console.error('loadDfcmTables函数未定义，请检查dfcmdata.js是否正确加载');
            }
            break;
        // 非标数据库表内容处理
        case 'am_archives_base':
            loadFeiBiaoContent('base');
            break;
        case 'am_archives_degradation':
            loadFeiBiaoContent('degradation');
            break;
        case 'am_archives_failure':
            loadFeiBiaoContent('failure');
            break;
        case 'am_archives_operation':
            loadArchivesOperationList();
            break;
        case 'am_archives_operation_test':
            loadFeiBiaoContent('operation_test');
            break;
        case 'am_archives_relation':
            loadFeiBiaoContent('relation');
            break;
        case 'am_knowledge_basic':
            loadKnowledgeContent('basic');
            break;
        case 'am_knowledge_entity':
            loadKnowledgeContent('entity');
            break;
        case 'am_knowledge_failure':
            loadKnowledgeContent('failure');
            break;
        case 'am_knowledge_operation':
            loadKnowledgeContent('operation');
            break;
        case 'am_knowledge_relation':
            loadKnowledgeContent('relation');
            break;
        // case 'am_aap_data':
        //     if (typeof loadAapDataList === 'function') {
        //         loadAapDataList();
        //     } else {
        //         showMessage('电机数据表模块未加载', 'error');
        //     }
        //     break;
        case 'am_aap_data_table':
            if (typeof loadAapDataList === 'function') {
                loadAapDataList();
            } else {
                showMessage('电机数据表模块未加载', 'error');
            }
            break;
        case 'am_aap_input':
            if (typeof loadAapInputList === 'function') {
                loadAapInputList();
            } else {
                showMessage('工况特定输入参数表模块未加载', 'error');
            }
            break;
        case 'am_aap_modelinfo':
            if (typeof loadAapModelInfoList === 'function') {
                loadAapModelInfoList();
            } else {
                showMessage('模型融合配置表模块未加载', 'error');
            }
            break;
        case 'am_aap_motorkn':
            if (typeof loadAapMotorKnList === 'function') {
                loadAapMotorKnList();
            } else {
                showMessage('电机知识表模块未加载', 'error');
            }
            break;
        case 'am_aap_output':
            if (typeof window.loadAapOutputList === 'function') {
                try {
                    window.loadAapOutputList();
                } catch (error) {
                    console.error('加载工况特定输出参数表时出错:', error);
                    showMessage('加载工况特定输出参数表失败: ' + error.message, 'error');
                }
            } else {
                console.error('loadAapOutputList函数未找到，请检查aap_output.js是否正确加载');
                showMessage('工况特定输出参数表模块未加载', 'error');
            }
            break;
        default:
            showMessage('未知的内容类型: ' + target, 'error');
    }
}

/**
 * 清理当前模块的资源
 * 在切换到新模块前调用
 */
function cleanupResources() {
    // 清理DFCM数据库模块资源
    if (typeof window.cleanupDfcmResources === 'function') {
        window.cleanupDfcmResources();
    }
    
    // 可在此处添加其他模块的资源清理函数
    
    // 清理内存中的大型对象，帮助垃圾回收
    if (window.gc) {
        try {
            window.gc();
        } catch (e) {
            console.log('手动垃圾回收不可用');
        }
    }
}

/**
 * 加载非标数据库相关内容
 * @param {string} contentType - 内容类型 (base|degradation|failure|operation|operation_test|relation)
 */
function loadFeiBiaoContent(contentType) {
    try {
        // 根据内容类型加载对应功能
        switch (contentType) {
            case 'base':
                if (typeof loadMotorBaseList === 'function') {
                    loadMotorBaseList();
                } else {
                    showMessage('电机基本信息管理模块未加载', 'error');
                }
                break;
            case 'degradation':
                if (typeof loadDegradationList === 'function') {
                    loadDegradationList();
                } else {
                    showMessage('性能退化数据管理模块未加载', 'error');
                }
                break;
            case 'failure':
                if (typeof loadFailureList === 'function') {
                    loadFailureList();
                } else {
                    showMessage('故障记录模块未加载或已被移除', 'warn');
                }
                break;
            case 'operation':
                if (typeof loadOperationList === 'function') {
                    loadOperationList();
                } else {
                    showMessage('请在index.html中添加运行数据模块JS文件 (operation.js)', 'warn');
                }
                break;
            case 'operation_test':
                if (typeof loadOperationTestList === 'function') {
                    loadOperationTestList();
                } else {
                    showMessage('运行测试数据模块未加载或已被移除', 'warn');
                }
                break;
            case 'relation':
                if (typeof loadStandardRelationList === 'function') {
                    loadStandardRelationList();
                } else {
                    showMessage('标准关联模块未加载或已被移除', 'warn');
                }
           
                break;
            default:
                showMessage('未知的内容类型: ' + contentType, 'error');
        }
    } catch (e) {
        console.error('加载非标数据库内容出错:', e);
        showMessage('加载内容失败: ' + e.message, 'error');
    }
}

// 添加全局变量来保持搜索状态
let currentSearchKeyword = '';

/**
 * 加载竞争机型数据
 */
function loadCompetingAircraft() {
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 发起请求获取数据
    fetch(`${API_BASE}/competing-aircraft?page=${currentPage}&size=15`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            renderCompetingAircraftTable(data);
        })
        .catch(error => {
            console.error('获取数据失败:', error);
            showMessage('获取数据失败: ' + error.message, 'error');
        });
}

/**
 * 渲染竞争机型表格
 * @param {Object} data - 分页数据
 */
function renderCompetingAircraftTable(data) {
    const mainContent = document.getElementById('mainContent');
    
    // 构建HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">竞争机型管理</h2>
            <button class="btn btn-primary" onclick="showCompetingAircraftForm()">新增</button>
        </div>
        
        <div class="search-box">
            <input type="text" class="search-input" id="searchInput" placeholder="输入关键词搜索..." value="${currentSearchKeyword}">
            <button class="search-btn" onclick="searchCompetingAircraft()">搜索</button>
            ${currentSearchKeyword ? '<button class="btn btn-default" onclick="clearSearch()">返回列表</button>' : ''}
        </div>
        
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>产品名称</th>
                    <th>飞行时间</th>
                    <th>起落次数</th>
                    <th>空中停车</th>
                    <th>创建时间</th>
                    <th>更新时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    // 填充数据行
    if (data.content && data.content.length > 0) {
        data.content.forEach(item => {
            html += `
                <tr>
                    <td>${item.id || ''}</td>
                    <td>${item.productName || ''}</td>
                    <td>${item.flightTime || ''}</td>
                    <td>${item.landingCount || ''}</td>
                    <td>${item.flightShutdown !== null && item.flightShutdown !== undefined ? item.flightShutdown : ''}</td>
                    <td>${formatDateTime(item.createTime) || ''}</td>
                    <td>${formatDateTime(item.updateTime) || ''}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewCompetingAircraft(${item.id})">查看</a>
                        <a href="javascript:void(0)" onclick="editCompetingAircraft(${item.id})">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteCompetingAircraft(${item.id})">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += '<tr><td colspan="8" style="text-align:center;">暂无数据</td></tr>';
    }
    
    html += `
            </tbody>
        </table>
    `;
    
    // 添加分页控件
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${currentPage <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentPage <= 0 ? 'void(0)' : 'gotoPage(' + (currentPage - 1) + ')'}">上一页</a>
                </li>
        `;
        
        // 页码
        for (let i = 0; i < data.totalPages; i++) {
            if (i === currentPage) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="gotoPage(${i})">${i + 1}</a></li>`;
            }
        }
        
        html += `
                <li class="${currentPage >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentPage >= data.totalPages - 1 ? 'void(0)' : 'gotoPage(' + (currentPage + 1) + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }
    
    // 更新内容区域
    mainContent.innerHTML = html;
}

/**
 * 清除搜索并返回列表
 */
function clearSearch() {
    currentSearchKeyword = '';  // 清除全局搜索关键词
    currentPage = 0;
    loadCompetingAircraft();
}

/**
 * 跳转到指定页码
 * @param {number} page - 页码
 */
function gotoPage(page) {
    currentPage = page;
    loadCompetingAircraft();
}

/**
 * 搜索竞争机型
 */
function searchCompetingAircraft() {
    const keyword = document.getElementById('searchInput').value.trim();
    currentSearchKeyword = keyword;  // 更新全局搜索关键词
    
    // 重置页码并加载数据
    currentPage = 0;
    
    // 构建搜索URL
    let url = `${API_BASE}/competing-aircraft?page=${currentPage}&size=15`;
    if (keyword) {
        url += `&keyword=${encodeURIComponent(keyword)}`;
    }
    
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 发起请求
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            renderCompetingAircraftTable(data);
        })
        .catch(error => {
            console.error('搜索失败:', error);
            showMessage('搜索失败: ' + error.message, 'error');
        });
}

/**
 * 显示竞争机型表单(新增/编辑)
 * @param {Object} data
 */
function showCompetingAircraftForm(data = null) {
    const mainContent = document.getElementById('mainContent');
    const isEdit = data !== null;
    
    // 构建表单HTML
    // 更新内容区域
    mainContent.innerHTML = `
        <div class="content-header">
            <h2 class="content-title">${isEdit ? '编辑' : '新增'}竞争机型</h2>
            <button class="btn btn-default" onclick="loadCompetingAircraft()">返回列表</button>
        </div>
        
        <form id="competingAircraftForm" class="data-form">
            ${isEdit ? `<input type="hidden" name="id" value="${data.id}">` : ''}
            
            <div class="form-group">
                <label for="productName">产品名称 <span class="required">*</span></label>
                <input type="text" id="productName" name="productName" class="form-control" value="${isEdit && data.productName ? data.productName : ''}" required>
            </div>
            
            <div class="form-group">
                <label for="componentReplacementRecord">部件拆换记录</label>
                <textarea id="componentReplacementRecord" name="componentReplacementRecord" class="form-control">${isEdit && data.componentReplacementRecord ? data.componentReplacementRecord : ''}</textarea>
            </div>
            
            <div class="form-group">
                <label for="componentRepairRecord">部件送修记录</label>
                <textarea id="componentRepairRecord" name="componentRepairRecord" class="form-control">${isEdit && data.componentRepairRecord ? data.componentRepairRecord : ''}</textarea>
            </div>
            
            <div class="form-group">
                <label for="engineApuReplacementRecord">发动机与APU拆换记录</label>
                <textarea id="engineApuReplacementRecord" name="engineApuReplacementRecord" class="form-control">${isEdit && data.engineApuReplacementRecord ? data.engineApuReplacementRecord : ''}</textarea>
            </div>
            
            <div class="form-group">
                <label for="engineApuOperatingHours">发动机与APU工作时间</label>
                <input type="number" id="engineApuOperatingHours" name="engineApuOperatingHours" class="form-control" step="0.01" value="${isEdit && data.engineApuOperatingHours ? data.engineApuOperatingHours : ''}">
            </div>
            
            <div class="form-group">
                <label for="flightTime">飞行时间</label>
                <input type="number" id="flightTime" name="flightTime" class="form-control" step="0.01" value="${isEdit && data.flightTime ? data.flightTime : ''}">
            </div>
            
            <div class="form-group">
                <label for="landingCount">起落次数</label>
                <input type="number" id="landingCount" name="landingCount" class="form-control" value="${isEdit && data.landingCount ? data.landingCount : ''}">
            </div>
            
            <div class="form-group">
                <label for="dailyOperationData">飞机每日运营数据</label>
                <textarea id="dailyOperationData" name="dailyOperationData" class="form-control">${isEdit && data.dailyOperationData ? data.dailyOperationData : ''}</textarea>
            </div>
            
            <div class="form-group">
                <label for="statusChangeRecord">飞机状态变更记录</label>
                <textarea id="statusChangeRecord" name="statusChangeRecord" class="form-control">${isEdit && data.statusChangeRecord ? data.statusChangeRecord : ''}</textarea>
            </div>
            
            <div class="form-group">
                <label for="faultReport">故障报告</label>
                <textarea id="faultReport" name="faultReport" class="form-control">${isEdit && data.faultReport ? data.faultReport : ''}</textarea>
            </div>
            
            <div class="form-group">
                <label for="flightShutdown">空中停车</label>
                <input type="number" id="flightShutdown" name="flightShutdown" class="form-control" step="0.01" value="${isEdit && data.flightShutdown ? data.flightShutdown : ''}">
            </div>
            
            <div class="form-group">
                <label for="operationalInterruptionReport">运行中断报告</label>
                <textarea id="operationalInterruptionReport" name="operationalInterruptionReport" class="form-control">${isEdit && data.operationalInterruptionReport ? data.operationalInterruptionReport : ''}</textarea>
            </div>
            
            <div class="form-group">
                <label for="usageDifficultyReport">使用困难报告</label>
                <textarea id="usageDifficultyReport" name="usageDifficultyReport" class="form-control">${isEdit && data.usageDifficultyReport ? data.usageDifficultyReport : ''}</textarea>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">保存</button>
                <button type="button" class="btn btn-default" onclick="loadCompetingAircraft()">取消</button>
            </div>
        </form>
    `;
    
    // 注册表单提交事件
    document.getElementById('competingAircraftForm').addEventListener('submit', function(e) {
        e.preventDefault();
        saveCompetingAircraft(this, isEdit);
    });
}

/**
 * 保存竞争机型数据
 * @param {HTMLFormElement} form - 表单元素
 * @param {boolean} isEdit - 是否为编辑模式
 */
function saveCompetingAircraft(form, isEdit) {
    // 表单验证
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    // 收集表单数据
    const formData = new FormData(form);
    const data = {};
    formData.forEach((value, key) => {
        data[key] = value;
    });
    
    // 转换数字字段
    if (data.engineApuOperatingHours) data.engineApuOperatingHours = parseFloat(data.engineApuOperatingHours);
    if (data.flightTime) data.flightTime = parseFloat(data.flightTime);
    if (data.landingCount) data.landingCount = parseInt(data.landingCount);
    if (data.flightShutdown) data.flightShutdown = parseFloat(data.flightShutdown);
    
    // 构建请求
    const url = isEdit 
        ? `${API_BASE}/competing-aircraft/${data.id}` 
        : `${API_BASE}/competing-aircraft`;
    
    const method = isEdit ? 'PUT' : 'POST';
    
    // 发送请求
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                throw new Error(text);
            });
        }
        return response.json();
    })
    .then(result => {
        showMessage(`竞争机型数据${isEdit ? '更新' : '添加'}成功!`, 'success');
        loadCompetingAircraft();
    })
    .catch(error => {
        console.error('保存失败:', error);
        showMessage(`保存失败: ${error.message}`, 'error');
    });
}

/**
 * 查看竞争机型详情
 * @param {number} id - 记录ID
 */
function viewCompetingAircraft(id) {
    // 发起请求获取详情
    fetch(`${API_BASE}/competing-aircraft/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            showCompetingAircraftDetail(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            showMessage('获取详情失败: ' + error.message, 'error');
        });
}

/**
 * 显示竞争机型详情
 * @param {Object} data - 详情数据
 */
function showCompetingAircraftDetail(data) {
    const mainContent = document.getElementById('mainContent');
    
    // 构建详情HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">竞争机型详情</h2>
            <button class="btn btn-default" onclick="loadCompetingAircraft()">返回列表</button>
        </div>
        
        <div class="data-detail">
            <div class="detail-section">
                <h3 class="section-title">基本信息</h3>
                <div class="detail-group">
                    <label>ID:</label>
                    <div>${data.id || '--'}</div>
                </div>
                
                <div class="detail-group">
                    <label>产品名称:</label>
                    <div>${data.productName || '--'}</div>
                </div>
                
                <div class="detail-group">
                    <label>飞行时间:</label>
                    <div>${data.flightTime || '--'} 小时</div>
                </div>
                
                <div class="detail-group">
                    <label>起落次数:</label>
                    <div>${data.landingCount || '--'} 次</div>
                </div>
                
                <div class="detail-group">
                    <label>空中停车:</label>
                    <div>${data.flightShutdown || '--'} 次</div>
                </div>
                
                <div class="detail-group">
                    <label>发动机与APU工作时间:</label>
                    <div>${data.engineApuOperatingHours || '--'} 小时</div>
                </div>
            </div>
            
            <div class="detail-section">
                <h3 class="section-title">记录数据</h3>
                <div class="detail-group">
                    <label>部件拆换记录:</label>
                    <div class="detail-content">
                        <pre>${formatTextarea(data.componentReplacementRecord) || '--'}</pre>
                    </div>
                </div>
                
                <div class="detail-group">
                    <label>部件送修记录:</label>
                    <div class="detail-content">
                        <pre>${formatTextarea(data.componentRepairRecord) || '--'}</pre>
                    </div>
                </div>
                
                <div class="detail-group">
                    <label>发动机与APU拆换记录:</label>
                    <div class="detail-content">
                        <pre>${formatTextarea(data.engineApuReplacementRecord) || '--'}</pre>
                    </div>
                </div>
                
                <div class="detail-group">
                    <label>飞机每日运营数据:</label>
                    <div class="detail-content">
                        <pre>${formatTextarea(data.dailyOperationData) || '--'}</pre>
                    </div>
                </div>
                
                <div class="detail-group">
                    <label>飞机状态变更记录:</label>
                    <div class="detail-content">
                        <pre>${formatTextarea(data.statusChangeRecord) || '--'}</pre>
                    </div>
                </div>
                
                <div class="detail-group">
                    <label>故障报告:</label>
                    <div class="detail-content">
                        <pre>${formatTextarea(data.faultReport) || '--'}</pre>
                    </div>
                </div>
                
                <div class="detail-group">
                    <label>运行中断报告:</label>
                    <div class="detail-content">
                        <pre>${formatTextarea(data.operationalInterruptionReport) || '--'}</pre>
                    </div>
                </div>
                
                <div class="detail-group">
                    <label>使用困难报告:</label>
                    <div class="detail-content">
                        <pre>${formatTextarea(data.usageDifficultyReport) || '--'}</pre>
                    </div>
                </div>
            </div>
            
            <div class="detail-section">
                <h3 class="section-title">系统信息</h3>
                <div class="detail-group">
                    <label>创建时间:</label>
                    <div>${formatDateTime(data.createTime) || '--'}</div>
                </div>
                
                <div class="detail-group">
                    <label>更新时间:</label>
                    <div>${formatDateTime(data.updateTime) || '--'}</div>
                </div>
            </div>
            
            <!-- 可靠性指标模块 -->
            <div class="detail-section reliability-metrics">
                <h3 class="section-title">可靠性指标</h3>
                <div id="reliability-container">
                    <div class="loading">指标数据加载中...</div>
                </div>
            </div>
            
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editCompetingAircraft(${data.id})"><i class="fa fa-edit"></i> 编辑</button>
                <button class="btn btn-danger" onclick="deleteCompetingAircraft(${data.id})"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-default" onclick="loadCompetingAircraft()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
    `;
    
    // 添加样式
    const style = document.createElement('style');
    style.textContent = `
        .detail-section {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #f7f9fc;
            border-radius: 5px;
            border-left: 4px solid #1890ff;
        }
        .section-title {
            font-size: 18px;
            margin-top: 0;
            margin-bottom: 15px;
            color: #333;
            font-weight: 600;
        }
        .reliability-metrics {
            margin-top: 20px;
            margin-bottom: 20px;
        }
        .error-container {
            color: #f5222d;
            padding: 10px;
            background-color: #fff1f0;
            border-radius: 4px;
            margin-bottom: 15px;
        }
    `;
    document.head.appendChild(style);
    
    // 更新内容区域
    mainContent.innerHTML = html;
    
    // 加载可靠性指标数据
    loadReliabilityMetrics(data.productName);
}

/**
 * 加载可靠性指标数据
 * @param {string} productName - 机型名称
 */
function loadReliabilityMetrics(productName) {
    const reliabilityContainer = document.getElementById('reliability-container');
    if (!reliabilityContainer) return;
    
    // 使用新的API路径 /metrics/reliability
    fetch(`${API_BASE}/competing-aircraft/metrics/reliability?productName=${encodeURIComponent(productName)}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取可靠性指标失败: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            renderReliabilityMetrics(data);
        })
        .catch(error => {
            console.error('获取可靠性指标失败:', error);
            reliabilityContainer.innerHTML = `
                <div class="error-container">
                    <p>获取可靠性指标失败: ${error.message}</p>
                </div>
            `;
        });
}

/**
 * 渲染可靠性指标
 * @param {Object} data - 指标数据
 */
function renderReliabilityMetrics(data) {
    const reliabilityContainer = document.getElementById('reliability-container');
    if (!reliabilityContainer) return;
    
    let html = '<div class="reliability-metrics-content">';
    
    // 空停率指标
    if (data.airShutdownRate !== null && data.airShutdownRate !== undefined) {
        html += `
            <div class="detail-group">
                <label>千小时空停率:</label>
                <div>${data.airShutdownRate.toFixed(2) + ' ‰'}</div>
            </div>
        `;
    }
    
    // 故障率指标
    if (data.faultRate !== null && data.faultRate !== undefined) {
        html += `
            <div class="detail-group">
                <label>千小时故障率:</label>
                <div>${data.faultRate.toFixed(2) + ' ‰'}</div>
            </div>
        `;
    }
    
    // 发动机拆换率指标
    if (data.engineReplacementRate !== null && data.engineReplacementRate !== undefined) {
        html += `
            <div class="detail-group">
                <label>发动机拆换率:</label>
                <div>${data.engineReplacementRate.toFixed(2) + ' 次/千小时'}</div>
            </div>
        `;
    }
    
    // MTBF指标
    if (data.mtbf !== null && data.mtbf !== undefined) {
        html += `
            <div class="detail-group">
                <label>平均故障间隔时间(MTBF):</label>
                <div>${data.mtbf.toFixed(2) + ' 千小时/次'}</div>
            </div>
        `;
    }
    
    // 可靠度指标
    if (data.reliability !== null && data.reliability !== undefined) {
        html += `
            <div class="detail-group">
                <label>可靠度:</label>
                <div>${(data.reliability * 100).toFixed(2) + '%'}</div>
            </div>
        `;
    }
    
    // 维修频率指标
    if (data.maintenanceFrequency !== null && data.maintenanceFrequency !== undefined) {
        html += `
            <div class="detail-group">
                <label>维修频率:</label>
                <div>${data.maintenanceFrequency.toFixed(2) + ' 次/千小时'}</div>
            </div>
        `;
    }
    
    // 使用困难报告频率指标
    if (data.difficultyReportRate !== null && data.difficultyReportRate !== undefined) {
        html += `
            <div class="detail-group">
                <label>使用困难报告频率:</label>
                <div>${data.difficultyReportRate.toFixed(2) + ' 次/千小时'}</div>
            </div>
        `;
    }
    
    html += '</div>';
    
    reliabilityContainer.innerHTML = html;
}

/**
 * 初始化详情页选项卡
 */
function initDetailTabs() {
    const tabNavItems = document.querySelectorAll('.tab-nav-item');
    const tabPanes = document.querySelectorAll('.tab-pane');
    
    tabNavItems.forEach(item => {
        item.addEventListener('click', () => {
            // 移除所有活动状态
            tabNavItems.forEach(navItem => navItem.classList.remove('active'));
            tabPanes.forEach(pane => pane.classList.remove('active'));
            
            // 激活当前选项卡
            item.classList.add('active');
            const targetId = item.getAttribute('data-tab');
            document.getElementById(targetId).classList.add('active');
        });
    });
}

/**
 * 打印竞争机型详情
 */
function printCompetingAircraftDetail() {
    window.print();
}

/**
 * 编辑竞争机型
 * @param {number} id - 记录ID
 */
function editCompetingAircraft(id) {
    // 发起请求获取详情
    fetch(`${API_BASE}/competing-aircraft/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            showCompetingAircraftForm(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            showMessage('获取详情失败: ' + error.message, 'error');
        });
}

/**
 * 删除竞争机型
 * @param {number} id - 记录ID
 */
function deleteCompetingAircraft(id) {
    if (!confirm('确定要删除这条记录吗？此操作不可恢复!')) {
        return;
    }
    
    // 发起删除请求
    fetch(`${API_BASE}/competing-aircraft/${id}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                throw new Error(text);
            });
        }
        showMessage('删除成功!', 'success');
        loadCompetingAircraft();
    })
    .catch(error => {
        console.error('删除失败:', error);
        showMessage('删除失败: ' + error.message, 'error');
    });
}

/**
 * 格式化日期时间
 * @param {string|object} datetime - 日期时间对象或字符串
 * @returns {string} 格式化后的日期时间
 */
function formatDateTime(datetime) {
    if (!datetime) return '';
    
    let date;
    if (typeof datetime === 'string') {
        date = new Date(datetime);
    } else if (datetime instanceof Object && datetime.time) {
        // 处理Timestamp对象
        date = new Date(datetime.time);
    } else {
        date = new Date(datetime);
    }
    
    if (isNaN(date.getTime())) return datetime.toString();
    
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

/**
 * 格式化文本区域内容，保留换行
 * @param {string} text - 文本内容
 * @returns {string} 格式化后的HTML
 */
function formatTextarea(text) {
    if (!text) return '';
    
    // 对HTML特殊字符进行转义，防止XSS攻击
    const escaped = String(text)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
    
    // 处理换行符
    return escaped;
}

/**
 * 高级搜索FMEAFMES
 */
function advancedSearchFMEAFMES() {
    // 获取搜索表单中的所有字段
    const searchForm = document.getElementById('advancedSearchForm');
    const formData = new FormData(searchForm);
    const searchParams = {};
    
    // 将表单数据转换为搜索参数
    for (const [key, value] of formData.entries()) {
        if (value) {
            searchParams[key] = value;
        }
    }
    
    // 获取分页和排序参数
    const page = document.getElementById('currentPage').value;
    const size = document.getElementById('pageSize').value;
    const sort = document.getElementById('sortField').value;
    
    // 构建查询字符串
    const queryParams = new URLSearchParams();
    queryParams.append('page', page);
    queryParams.append('size', size);
    if (sort) {
        queryParams.append('sort', sort);
    }
    
    // 添加搜索参数
    for (const [key, value] of Object.entries(searchParams)) {
        queryParams.append(key, value);
    }
    
    // 构建URL
    const url = `${API_BASE}/fmeafmes/advanced-search?${queryParams.toString()}`;
    
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 发起请求
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            renderFMEAFMESTable(data);
        })
        .catch(error => {
            console.error('高级搜索失败:', error);
            showMessage('高级搜索失败: ' + error.message, 'error');
        });
}

/**
 * 渲染高级搜索表单
 */
function renderAdvancedSearchForm() {
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = `
        <div class="content-header">
            <h2 class="content-title">失效模式和影响分析 - 高级搜索</h2>
            <button class="btn btn-default" onclick="loadFMEAFMES()"><i class="fa fa-arrow-left"></i> 返回列表</button>
        </div>
        
        <div class="advanced-search-container data-form">
            <form id="advancedSearchForm" onsubmit="event.preventDefault(); advancedSearchFMEAFMES();">
                <input type="hidden" id="currentPage" name="page" value="0">
                <input type="hidden" id="pageSize" name="size" value="10">
                
                <div class="row">
                    <div class="col-md-6">
                <div class="form-group">
                            <label for="name">产品或功能名称</label>
                    <input type="text" id="name" name="name" class="form-control">
                </div>
                    </div>
                    
                    <div class="col-md-6">
                <div class="form-group">
                    <label for="exact_id">ID（精确匹配）</label>
                    <input type="text" id="exact_id" name="exact_id" class="form-control">
                </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="system">系统</label>
                            <input type="text" id="system" name="system" class="form-control">
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="subsystem">子系统</label>
                            <input type="text" id="subsystem" name="subsystem" class="form-control">
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="fMode">故障模式</label>
                            <input type="text" id="fMode" name="fMode" class="form-control">
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="hazardRating">危害等级</label>
                            <input type="text" id="hazardRating" name="hazardRating" class="form-control">
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6">
                <div class="form-group">
                    <label for="createTimeStart">创建时间范围（开始）</label>
                    <input type="datetime-local" id="createTimeStart" name="createTimeStart" class="form-control">
                </div>
                    </div>
                    
                    <div class="col-md-6">
                <div class="form-group">
                    <label for="createTimeEnd">创建时间范围（结束）</label>
                    <input type="datetime-local" id="createTimeEnd" name="createTimeEnd" class="form-control">
                </div>
                </div>
                </div>
                
                <div class="form-group">
                    <label for="sortField">排序字段</label>
                    <select id="sortField" name="sort" class="form-control">
                        <option value="">-- 请选择 --</option>
                        <option value="id,asc">ID 升序</option>
                        <option value="id,desc">ID 降序</option>
                        <option value="name,asc">产品名称 升序</option>
                        <option value="name,desc">产品名称 降序</option>
                        <option value="system,asc">系统 升序</option>
                        <option value="system,desc">系统 降序</option>
                        <option value="createTime,asc">创建时间 升序</option>
                        <option value="createTime,desc">创建时间 降序</option>
                    </select>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i> 搜索</button>
                    <button type="button" class="btn btn-default" onclick="resetSearchForm()"><i class="fa fa-refresh"></i> 重置</button>
                    <button type="button" class="btn btn-default" onclick="loadFMEAFMES()"><i class="fa fa-times"></i> 取消</button>
                </div>
            </form>
        </div>
    `;
    
    // 添加栅格化CSS
    addGridStyles();
}

/**
 * 添加栅格化样式
 */
function addGridStyles() {
    // 检查是否已添加样式
    if (!document.getElementById('grid-styles')) {
        const style = document.createElement('style');
        style.id = 'grid-styles';
        style.textContent = `
            .row {
                display: flex;
                flex-wrap: wrap;
                margin-right: -15px;
                margin-left: -15px;
            }
            .col-md-6 {
                flex: 0 0 50%;
                max-width: 50%;
                padding-right: 15px;
                padding-left: 15px;
            }
            @media (max-width: 768px) {
                .col-md-6 {
                    flex: 0 0 100%;
                    max-width: 100%;
                }
            }
            .advanced-search-container {
                background-color: #fff;
                padding: 20px;
                border-radius: 4px;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
                margin-bottom: 20px;
            }
        `;
        document.head.appendChild(style);
    }
}

/**
 * 重置搜索表单
 */
function resetSearchForm() {
    const form = document.getElementById('advancedSearchForm');
    form.reset();
    advancedSearchFMEAFMES();
}

/**
 * 加载FMEAFMES数据
 */
function loadFMEAFMES() {
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 发起请求获取数据
    fetch(`${API_BASE}/fmeafmes/page?page=${currentPage}&size=${pageSize}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            renderFMEAFMESTable(data);
        })
        .catch(error => {
            console.error('获取数据失败:', error);
            showMessage('获取数据失败: ' + error.message, 'error');
        });
}

/**
 * 渲染FMEAFMES表格
 * @param {Object} data - 分页数据
 */
function renderFMEAFMESTable(data) {
    const mainContent = document.getElementById('mainContent');
    
    // 构建HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">失效模式和影响分析</h2>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="showFMEAFMESForm()">新增</button>
            </div>
        </div>
        
        <div class="search-box">
            <input type="text" class="search-input" id="searchInput" placeholder="输入关键词搜索...">
            <button class="search-btn" onclick="searchFMEAFMES()">搜索</button>
        </div>
        
        <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>产品名称</th>
                    <th>系统</th>
                    <th>子系统</th>
                    <th>故障模式</th>
                    <th>危害等级</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    // 填充数据行
    if (data.content && data.content.length > 0) {
        data.content.forEach(item => {
            html += `
                <tr>
                    <td>${item.id || ''}</td>
                    <td>${item.name || ''}</td>
                    <td>${item.systemName || ''}</td>
                    <td>${item.subsystem || ''}</td>
                    <td>${item.fMode || ''}</td>
                    <td>${item.hazardRating || ''}</td>
                    <td>${formatDateTime(item.createTime) || ''}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewFMEAFMES(${item.id})">查看</a>
                        <a href="javascript:void(0)" onclick="editFMEAFMES(${item.id})">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteFMEAFMES(${item.id})">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += '<tr><td colspan="8" style="text-align:center;">暂无数据</td></tr>';
    }
    
    html += `
            </tbody>
        </table>
        </div>
    `;
    
    // 添加分页控件
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${currentPage <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentPage <= 0 ? 'void(0)' : 'gotoPage(' + (currentPage - 1) + ')'}">上一页</a>
                </li>
        `;
        
        // 页码
        for (let i = 0; i < data.totalPages; i++) {
            if (i === currentPage) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="gotoPage(${i})">${i + 1}</a></li>`;
            }
        }
        
        html += `
                <li class="${currentPage >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentPage >= data.totalPages - 1 ? 'void(0)' : 'gotoPage(' + (currentPage + 1) + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }
    
    // 更新内容区域
    mainContent.innerHTML = html;
}

/**
 * 搜索FMEAFMES
 */
function searchFMEAFMES() {
    const keyword = document.getElementById('searchInput').value.trim();
    
    // 重置页码并加载数据
    currentPage = 0;
    
    // 构建搜索URL
    let url = `${API_BASE}/fmeafmes/search?page=${currentPage}&size=${pageSize}`;
    if (keyword) {
        url += `&keyword=${encodeURIComponent(keyword)}`;
    }
    
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 发起请求
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            renderFMEAFMESTable(data);
        })
        .catch(error => {
            console.error('搜索失败:', error);
            showMessage('搜索失败: ' + error.message, 'error');
        });
}

/**
 * 显示FMEAFMES表单(新增/编辑)
 * @param {Object} data - 已有数据(编辑时传入)
 */
function showFMEAFMESForm(data = null) {
    const mainContent = document.getElementById('mainContent');
    const isEdit = data !== null;
    
    // 构建表单HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">${isEdit ? '编辑' : '新增'}失效模式和影响分析</h2>
            <button class="btn btn-default" onclick="loadFMEAFMES()">返回列表</button>
        </div>
        
        <form id="fmeafmesForm" class="data-form">
            ${isEdit ? `<input type="hidden" name="id" value="${data.id}">` : ''}
            
            <div class="form-group">
                <label for="name">产品或功能名称 <span class="required">*</span></label>
                <input type="text" id="name" name="name" class="form-control" value="${isEdit && data.name ? data.name : ''}" required>
            </div>
            
            <div class="form-group">
                <label for="initialConventionLevel">初始约定层次</label>
                <input type="text" id="initialConventionLevel" name="initialConventionLevel" class="form-control" value="${isEdit && data.initialConventionLevel ? data.initialConventionLevel : ''}">
            </div>
            
            <div class="form-group">
                <label for="conventionLevel">约定层次</label>
                <input type="text" id="conventionLevel" name="conventionLevel" class="form-control" value="${isEdit && data.conventionLevel ? data.conventionLevel : ''}">
            </div>
            
            <div class="form-group">
                <label for="systemName">被分析产品所在系统</label>
                <input type="text" id="systemName" name="systemName" class="form-control" value="${isEdit && data.systemName ? data.systemName : ''}">
            </div>
            
            <div class="form-group">
                <label for="subsystem">被分析产品所在子系统</label>
                <input type="text" id="subsystem" name="subsystem" class="form-control" value="${isEdit && data.subsystem ? data.subsystem : ''}">
            </div>
            
            <div class="form-group">
                <label for="fMode">故障模式</label>
                <input type="text" id="fMode" name="fMode" class="form-control" value="${isEdit && data.fMode ? data.fMode : ''}">
            </div>
            
            <div class="form-group">
                <label for="fCause">故障原因</label>
                <input type="text" id="fCause" name="fCause" class="form-control" value="${isEdit && data.fCause ? data.fCause : ''}">
            </div>
            
            <div class="form-group">
                <label for="flightPhase">飞行阶段</label>
                <input type="text" id="flightPhase" name="flightPhase" class="form-control" value="${isEdit && data.flightPhase ? data.flightPhase : ''}">
            </div>
            
            <div class="form-group">
                <label for="fEffects">故障影响</label>
                <textarea id="fEffects" name="fEffects" class="form-control">${isEdit && data.fEffects ? data.fEffects : ''}</textarea>
            </div>
            
            <div class="form-group">
                <label for="singleFailureRate">单个产品或功能模块失效率</label>
                <input type="number" id="singleFailureRate" name="singleFailureRate" step="0.0001" class="form-control" value="${isEdit && data.singleFailureRate ? data.singleFailureRate : ''}">
            </div>
            
            <div class="form-group">
                <label for="fmFailureRate">故障模式失效率</label>
                <input type="number" id="fmFailureRate" name="fmFailureRate" step="0.0001" class="form-control" value="${isEdit && data.fmFailureRate ? data.fmFailureRate : ''}">
            </div>
            
            <div class="form-group">
                <label for="hazardRating">危害等级</label>
                <input type="text" id="hazardRating" name="hazardRating" class="form-control" value="${isEdit && data.hazardRating ? data.hazardRating : ''}">
            </div>
            
            <div class="form-group">
                <label for="detectionMethod">检测方法</label>
                <input type="text" id="detectionMethod" name="detectionMethod" class="form-control" value="${isEdit && data.detectionMethod ? data.detectionMethod : ''}">
            </div>
            
            <div class="form-group">
                <label for="correctiveAction">纠正措施</label>
                <textarea id="correctiveAction" name="correctiveAction" class="form-control">${isEdit && data.correctiveAction ? data.correctiveAction : ''}</textarea>
            </div>
            
            <div class="form-group">
                <label for="highFrequency">高频通信</label>
                <input type="text" id="highFrequency" name="highFrequency" class="form-control" value="${isEdit && data.highFrequency ? data.highFrequency : ''}">
            </div>
            
            <div class="form-group">
                <label for="hfVoiceCommunicationLink">提供高频语音通信链路</label>
                <input type="text" id="hfVoiceCommunicationLink" name="hfVoiceCommunicationLink" class="form-control" value="${isEdit && data.hfVoiceCommunicationLink ? data.hfVoiceCommunicationLink : ''}">
            </div>
            
            <div class="form-group">
                <label for="hfTransceiverFailureRate">高频收发机失效率</label>
                <input type="number" id="hfTransceiverFailureRate" name="hfTransceiverFailureRate" step="0.0001" class="form-control" value="${isEdit && data.hfTransceiverFailureRate ? data.hfTransceiverFailureRate : ''}">
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">保存</button>
                <button type="button" class="btn btn-default" onclick="loadFMEAFMES()">取消</button>
            </div>
        </form>
    `;
    
    // 更新内容区域
    mainContent.innerHTML = html;
    
    // 注册表单提交事件
    document.getElementById('fmeafmesForm').addEventListener('submit', function(e) {
        e.preventDefault();
        saveFMEAFMES(this, isEdit);
    });
}

/**
 * 保存FMEAFMES数据
 * @param {HTMLFormElement} form - 表单元素
 * @param {boolean} isEdit - 是否为编辑模式
 */
function saveFMEAFMES(form, isEdit) {
    // 表单验证
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    // 收集表单数据
    const formData = new FormData(form);
    const data = {};
    formData.forEach((value, key) => {
        data[key] = value;
    });
    
    // 转换数字字段
    if (data.singleFailureRate) data.singleFailureRate = parseFloat(data.singleFailureRate);
    if (data.fmFailureRate) data.fmFailureRate = parseFloat(data.fmFailureRate);
    if (data.hfTransceiverFailureRate) data.hfTransceiverFailureRate = parseFloat(data.hfTransceiverFailureRate);
    
    // 设置创建时间（只在新增时设置）
    if (!isEdit) {
        // 使用当前日期时间
        const now = new Date();
        data.createTime = now.toISOString().slice(0, 19).replace('T', ' ');
    }
    
    // 不设置updateTime字段，让MySQL自动处理ON UPDATE CURRENT_TIMESTAMP
    
    // 构建请求
    const url = isEdit 
        ? `${API_BASE}/fmeafmes/${data.id}` 
        : `${API_BASE}/fmeafmes`;
    
    const method = isEdit ? 'PUT' : 'POST';
    
    // 发送请求
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                throw new Error(text);
            });
        }
        return response.json();
    })
    .then(result => {
        showMessage(`失效模式和影响分析数据${isEdit ? '更新' : '添加'}成功!`, 'success');
        loadFMEAFMES();
    })
    .catch(error => {
        console.error('保存失败:', error);
        showMessage(`保存失败: ${error.message}`, 'error');
    });
}

/**
 * 查看FMEAFMES详情
 * @param {number} id - 记录ID
 */
function viewFMEAFMES(id) {
    // 发起请求获取详情
    fetch(`${API_BASE}/fmeafmes/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {

            showFMEAFMESDetail(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            showMessage('获取详情失败: ' + error.message, 'error');
        });
}

/**
 * 显示FMEAFMES详情
 * @param {Object} data - 详情数据
 */
function showFMEAFMESDetail(data) {
    const mainContent = document.getElementById('mainContent');
    
    // 构建详情HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">失效模式和影响分析详情</h2>
            <div class="content-actions">
                <button class="btn btn-default" onclick="loadFMEAFMES()"></i> 返回列表</button>
            </div>
        </div>
        
        <div class="data-detail">
            <div class="detail-group"><label>ID:</label><div>${data.id || '--'}</div></div>
            <div class="detail-group"><label>产品或功能名称:</label><div>${data.name || '--'}</div></div>
            <div class="detail-group"><label>初始约定层次:</label><div>${data.initialConventionLevel || '--'}</div></div>
            <div class="detail-group"><label>约定层次:</label><div>${data.conventionLevel || '--'}</div></div>
            <div class="detail-group"><label>被分析产品所在系统:</label><div>${data.systemName || '--'}</div></div>
            <div class="detail-group"><label>被分析产品所在子系统:</label><div>${data.subsystem || '--'}</div></div>
            <div class="detail-group"><label>故障模式:</label><div>${data.fMode || '--'}</div></div>
            <div class="detail-group"><label>故障原因:</label><div>${data.fCause || '--'}</div></div>
            <div class="detail-group"><label>飞行阶段:</label><div>${data.flightPhase || '--'}</div></div>
            <div class="detail-group"><label>故障影响:</label><div><pre>${formatTextarea(data.fEffects) || '--'}</pre></div></div>
            <div class="detail-group"><label>单个产品或功能模块失效率:</label><div>${data.singleFailureRate ? data.singleFailureRate.toFixed(4) : '--'}</div></div>
            <div class="detail-group"><label>故障模式失效率:</label><div>${data.fmFailureRate ? data.fmFailureRate.toFixed(4) : '--'}</div></div>
            <div class="detail-group"><label>危害等级:</label><div>${data.hazardRating || '--'}</div></div>
            <div class="detail-group"><label>检测方法:</label><div>${data.detectionMethod || '--'}</div></div>
            <div class="detail-group"><label>纠正措施:</label><div><pre>${formatTextarea(data.correctiveAction) || '--'}</pre></div></div>
            <div class="detail-group"><label>高频通信:</label><div>${data.highFrequency || '--'}</div></div>
            <div class="detail-group"><label>提供高频语音通信链路:</label><div>${data.hfVoiceCommunicationLink || '--'}</div></div>
            <div class="detail-group"><label>高频收发机失效率:</label><div>${data.hfTransceiverFailureRate ? data.hfTransceiverFailureRate.toFixed(4) : '--'}</div></div>
            <div class="detail-group"><label>创建时间:</label><div>${formatDateTime(data.createTime) || '--'}</div></div>
            <div class="detail-group"><label>更新时间:</label><div>${formatDateTime(data.updateTime) || '--'}</div></div>
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editFMEAFMES(${data.id})"><i class="fa fa-edit"></i> 编辑</button>
                <button class="btn btn-danger" onclick="deleteFMEAFMES(${data.id})"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-default" onclick="loadFMEAFMES()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
    `;
    
    // 更新内容区域
    mainContent.innerHTML = html;
}

/**
 * 加载运营数据
 */
function loadOperation() {
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 发起请求获取数据
    fetch(`${API_BASE}/operations/page?page=${currentPage}&size=${pageSize}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            renderOperationTable(data);
        })
        .catch(error => {
            console.error('获取数据失败:', error);
            showMessage('获取数据失败: ' + error.message, 'error');
        });
}

/**
 * 渲染运营数据表格
 * @param {Object} data - 分页数据
 */
function renderOperationTable(data) {
    const mainContent = document.getElementById('mainContent');
    
    // 构建HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">运营数据</h2>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="showOperationForm()">新增</button>
            </div>
        </div>
        
        <div class="search-box">
            <input type="text" class="search-input" id="searchInput" placeholder="输入关键词搜索...">
            <button class="search-btn" onclick="searchOperation()">搜索</button>
        </div>
        
        <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>产品名称</th>
                    <th>系统</th>
                    <th>子系统</th>
                    <th>故障模式</th>
                    <th>单次故障率</th>
                    <th>危害等级</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    // 填充数据行
    if (data.content && data.content.length > 0) {
        data.content.forEach(item => {
            html += `
                <tr>
                    <td>${item.id || ''}</td>
                    <td>${item.name || ''}</td>
                    <td>${item.system || ''}</td>
                    <td>${item.subsystem || ''}</td>
                    <td>${item.fMode || ''}</td>
                    <td>${item.singleFailureRate || ''}</td>
                    <td>${item.hazardRating || ''}</td>
                    <td>${formatDateTime(item.createTime) || ''}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewOperation(${item.id})">查看</a>
                        <a href="javascript:void(0)" onclick="editOperation(${item.id})">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteOperation(${item.id})">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += '<tr><td colspan="9" style="text-align:center;">暂无数据</td></tr>';
    }
    
    html += `
            </tbody>
        </table>
        </div>
    `;
    
    // 添加分页控件
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${currentPage <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentPage <= 0 ? 'void(0)' : 'gotoPage(' + (currentPage - 1) + ')'}">上一页</a>
                </li>
        `;
        
        // 页码
        for (let i = 0; i < data.totalPages; i++) {
            if (i === currentPage) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="gotoPage(${i})">${i + 1}</a></li>`;
            }
        }
        
        html += `
                <li class="${currentPage >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentPage >= data.totalPages - 1 ? 'void(0)' : 'gotoPage(' + (currentPage + 1) + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }
    
    // 更新内容区域
    mainContent.innerHTML = html;
}

/**
 * 搜索运营数据
 */
function searchOperation() {
    const keyword = document.getElementById('searchInput').value.trim();
    
    // 重置页码并加载数据
    currentPage = 0;
    
    // 构建搜索URL
    let url = `${API_BASE}/operations/search?page=${currentPage}&size=${pageSize}`;
    if (keyword) {
        url += `&keyword=${encodeURIComponent(keyword)}`;
    }
    
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 发起请求
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            renderOperationTable(data);
        })
        .catch(error => {
            console.error('搜索失败:', error);
            showMessage('搜索失败: ' + error.message, 'error');
        });
}

/**
 * 显示运营数据表单(新增/编辑)
 * @param {Object} data - 已有数据(编辑时传入)
 */
function showOperationForm(data = null) {
    const mainContent = document.getElementById('mainContent');
    const isEdit = data !== null;
    
    // 构建表单HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">${isEdit ? '编辑' : '新增'}运营数据</h2>
            <button class="btn btn-default" onclick="loadOperation()">返回列表</button>
        </div>
        
        <form id="operationForm" class="data-form">
            ${isEdit ? `<input type="hidden" name="id" value="${data.id}">` : ''}
            
            <div class="form-group">
                <label for="name">产品或功能名称 <span class="required">*</span></label>
                <input type="text" id="name" name="name" class="form-control" value="${isEdit && data.name ? data.name : ''}" required>
            </div>
            
            <div class="form-group">
                <label for="initialConventionLevel">初始约定层次</label>
                <input type="text" id="initialConventionLevel" name="initialConventionLevel" class="form-control" value="${isEdit && data.initialConventionLevel ? data.initialConventionLevel : ''}">
            </div>
            
            <div class="form-group">
                <label for="conventionLevel">约定层次</label>
                <input type="text" id="conventionLevel" name="conventionLevel" class="form-control" value="${isEdit && data.conventionLevel ? data.conventionLevel : ''}">
            </div>
            
            <div class="form-group">
                <label for="system">被分析产品所在系统</label>
                <input type="text" id="system" name="system" class="form-control" value="${isEdit && data.system ? data.system : ''}">
            </div>
            
            <div class="form-group">
                <label for="subsystem">被分析产品所在子系统</label>
                <input type="text" id="subsystem" name="subsystem" class="form-control" value="${isEdit && data.subsystem ? data.subsystem : ''}">
            </div>
            
            <div class="form-group">
                <label for="fMode">故障模式</label>
                <input type="text" id="fMode" name="fMode" class="form-control" value="${isEdit && data.fMode ? data.fMode : ''}">
            </div>
            
            <div class="form-group">
                <label for="fCause">故障原因</label>
                <input type="text" id="fCause" name="fCause" class="form-control" value="${isEdit && data.fCause ? data.fCause : ''}">
            </div>
            
            <div class="form-group">
                <label for="flightPhase">飞行阶段</label>
                <input type="text" id="flightPhase" name="flightPhase" class="form-control" value="${isEdit && data.flightPhase ? data.flightPhase : ''}">
            </div>
            
            <div class="form-group">
                <label for="fEffects">故障影响</label>
                <textarea id="fEffects" name="fEffects" class="form-control">${isEdit && data.fEffects ? data.fEffects : ''}</textarea>
            </div>
            
            <div class="form-group">
                <label for="singleFailureRate">单次故障率</label>
                <input type="number" id="singleFailureRate" name="singleFailureRate" step="0.000001" class="form-control" value="${isEdit && data.singleFailureRate ? data.singleFailureRate : ''}">
            </div>
            
            <div class="form-group">
                <label for="fmFailureRate">故障模式故障率</label>
                <input type="number" id="fmFailureRate" name="fmFailureRate" step="0.000001" class="form-control" value="${isEdit && data.fmFailureRate ? data.fmFailureRate : ''}">
            </div>
            
            <div class="form-group">
                <label for="hazardRating">危害等级</label>
                <input type="text" id="hazardRating" name="hazardRating" class="form-control" value="${isEdit && data.hazardRating ? data.hazardRating : ''}">
            </div>
            
            <div class="form-group">
                <label for="detectionMethod">检测方法</label>
                <input type="text" id="detectionMethod" name="detectionMethod" class="form-control" value="${isEdit && data.detectionMethod ? data.detectionMethod : ''}">
            </div>
            
            <div class="form-group">
                <label for="correctiveAction">纠正措施</label>
                <textarea id="correctiveAction" name="correctiveAction" class="form-control">${isEdit && data.correctiveAction ? data.correctiveAction : ''}</textarea>
            </div>
            
            <div class="form-group">
                <label for="highFrequency">高频通信</label>
                <input type="text" id="highFrequency" name="highFrequency" class="form-control" value="${isEdit && data.highFrequency ? data.highFrequency : ''}">
            </div>
            
            <div class="form-group">
                <label for="hfVoiceCommunicationLink">提供高频语音通信链路</label>
                <input type="text" id="hfVoiceCommunicationLink" name="hfVoiceCommunicationLink" class="form-control" value="${isEdit && data.hfVoiceCommunicationLink ? data.hfVoiceCommunicationLink : ''}">
            </div>
            
            <div class="form-group">
                <label for="hfTransceiverFailureRate">高频收发机失效率</label>
                <input type="number" id="hfTransceiverFailureRate" name="hfTransceiverFailureRate" step="0.0001" class="form-control" value="${isEdit && data.hfTransceiverFailureRate ? data.hfTransceiverFailureRate : ''}">
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">保存</button>
                <button type="button" class="btn btn-default" onclick="loadOperation()">取消</button>
            </div>
        </form>
    `;
    
    // 更新内容区域
    mainContent.innerHTML = html;
    
    // 注册表单提交事件
    document.getElementById('operationForm').addEventListener('submit', function(e) {
        e.preventDefault();
        saveOperation(this, isEdit);
    });
}

/**
 * 保存运营数据
 * @param {HTMLFormElement} form - 表单元素
 * @param {boolean} isEdit - 是否为编辑模式
 */
function saveOperation(form, isEdit) {
    // 表单验证
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    // 收集表单数据
    const formData = new FormData(form);
    const data = {};
    formData.forEach((value, key) => {
        data[key] = value;
    });
    
    // 构建请求
    const url = isEdit 
        ? `${API_BASE}/operations/${data.id}` 
        : `${API_BASE}/operations`;
    
    const method = isEdit ? 'PUT' : 'POST';
    
    // 发送请求
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                throw new Error(text);
            });
        }
        return response.json();
    })
    .then(result => {
        showMessage(`运营数据${isEdit ? '更新' : '添加'}成功!`, 'success');
        loadOperation();
    })
    .catch(error => {
        console.error('保存失败:', error);
        showMessage(`保存失败: ${error.message}`, 'error');
    });
}

/**
 * 查看运营数据详情
 * @param {number} id - 记录ID
 */
function viewOperation(id) {
    // 发起请求获取详情
    fetch(`${API_BASE}/operations/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            showOperationDetail(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            showMessage('获取详情失败: ' + error.message, 'error');
        });
}

/**
 * 显示运营数据详情
 * @param {Object} data - 详情数据
 */
function showOperationDetail(data) {
    const mainContent = document.getElementById('mainContent');
    
    // 构建详情HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">运营数据详情</h2>
            <div class="content-actions">
                <button class="btn btn-default" onclick="loadOperation()"></i> 返回列表</button>
            </div>
        </div>
        
        <div class="data-detail">
            <div class="detail-group"><label>ID:</label><div>${data.id || '--'}</div></div>
            <div class="detail-group"><label>产品或功能名称:</label><div>${data.name || '--'}</div></div>
            <div class="detail-group"><label>初始约定层次:</label><div>${data.initialConventionLevel || '--'}</div></div>
            <div class="detail-group"><label>约定层次:</label><div>${data.conventionLevel || '--'}</div></div>
            <div class="detail-group"><label>被分析产品所在系统:</label><div>${data.system || '--'}</div></div>
            <div class="detail-group"><label>被分析产品所在子系统:</label><div>${data.subsystem || '--'}</div></div>
            <div class="detail-group"><label>故障模式:</label><div>${data.fMode || '--'}</div></div>
            <div class="detail-group"><label>故障原因:</label><div>${data.fCause || '--'}</div></div>
            <div class="detail-group"><label>飞行阶段:</label><div>${data.flightPhase || '--'}</div></div>
            <div class="detail-group"><label>故障影响:</label><div><pre>${formatTextarea(data.fEffects) || '--'}</pre></div></div>
            <div class="detail-group"><label>单个产品或功能模块失效率:</label><div>${data.singleFailureRate ? data.singleFailureRate.toFixed(4) : '--'}</div></div>
            <div class="detail-group"><label>故障模式失效率:</label><div>${data.fmFailureRate ? data.fmFailureRate.toFixed(4) : '--'}</div></div>
            <div class="detail-group"><label>危害等级:</label><div>${data.hazardRating || '--'}</div></div>
            <div class="detail-group"><label>检测方法:</label><div>${data.detectionMethod || '--'}</div></div>
            <div class="detail-group"><label>纠正措施:</label><div><pre>${formatTextarea(data.correctiveAction) || '--'}</pre></div></div>
            <div class="detail-group"><label>高频通信:</label><div>${data.highFrequency || '--'}</div></div>
            <div class="detail-group"><label>提供高频语音通信链路:</label><div>${data.hfVoiceCommunicationLink || '--'}</div></div>
            <div class="detail-group"><label>高频收发机失效率:</label><div>${data.hfTransceiverFailureRate ? data.hfTransceiverFailureRate.toFixed(4) : '--'}</div></div>
            <div class="detail-group"><label>创建时间:</label><div>${formatDateTime(data.createTime) || '--'}</div></div>
            <div class="detail-group"><label>更新时间:</label><div>${formatDateTime(data.updateTime) || '--'}</div></div>
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editOperation(${data.id})"><i class="fa fa-edit"></i> 编辑</button>
                <button class="btn btn-danger" onclick="deleteOperation(${data.id})"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-default" onclick="loadOperation()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
    `;
    
    // 更新内容区域
    mainContent.innerHTML = html;
}

/**
 * 编辑运营数据
 * @param {number} id - 记录ID
 */
function editOperation(id) {
    // 发起请求获取详情
    fetch(`${API_BASE}/operations/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            showOperationForm(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            showMessage('获取详情失败: ' + error.message, 'error');
        });
}

/**
 * 删除运营数据
 * @param {number} id - 记录ID
 */
function deleteOperation(id) {
    if (!confirm('确定要删除这条记录吗？此操作不可恢复!')) {
        return;
    }
    
    // 发起删除请求
    fetch(`${API_BASE}/operations/${id}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                throw new Error(text);
            });
        }
        showMessage('删除成功!', 'success');
        loadOperation();
    })
    .catch(error => {
        console.error('删除失败:', error);
        showMessage('删除失败: ' + error.message, 'error');
    });
}

/**
 * 获取API路径映射
 * 确保前端与后端路径一致
 */
function getApiPath(module, action) {
    const API_BASE = '/api';
    
    // 模块路径映射
    const MODULE_PATHS = {
        competing_aircraft: 'competing-aircraft',
        fmeafmes: 'fmeafmes',
        operation: 'operations',
        feibiao: {
            base: 'feibiao/motor-base',
            degradation: 'feibiao/degradation',
            failure: 'feibiao/failure',
            operation: 'feibiao/operation',
            operation_test: 'feibiao/operation-test',
            relation: 'feibiao/relation'
        },
        knowledge: {
            basic: 'feibiao/knowledge/basic',
            entity: 'feibiao/knowledge/entity',
            failure: 'feibiao/knowledge/failure'
        }
    };
    
    // 获取模块路径
    let modulePath;
    if (typeof MODULE_PATHS[module] === 'object') {
        // 处理嵌套模块 (如feibiao下的子模块)
        const parentModule = module;
        const childModule = action;
        modulePath = MODULE_PATHS[parentModule][childModule];
        return `${API_BASE}/${modulePath}`;
    } else {
        modulePath = MODULE_PATHS[module] || module;
        
        // 处理操作路径
        let actionPath = '';
        if (action) {
            actionPath = `/${action}`;
        }
        
        return `${API_BASE}/${modulePath}${actionPath}`;
    }
}

/**
 * 加载电机向量知识库菜单
 * 显示电机基础信息和知识图谱实体两个选项
 */
function loadKnowledgeMenu() {
    const mainContent = document.getElementById('mainContent');
    
    // 构建HTML
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机向量知识库</h2>
        </div>
        
        <div class="knowledge-menu">
            <div class="knowledge-menu-item" onclick="loadKnowledgeContent('basic')">
                <i class="fa fa-database knowledge-icon"></i>
                <h3>电机基础信息</h3>
                <p>管理电机型号、生产厂商、额定参数等基础数据</p>
            </div>
            <div class="knowledge-menu-item" onclick="loadKnowledgeContent('entity')">
                <i class="fa fa-sitemap knowledge-icon"></i>
                <h3>知识图谱实体</h3>
                <p>管理知识图谱核心实体数据</p>
            </div>
            <div class="knowledge-menu-item" onclick="loadKnowledgeContent('failure')">
                <i class="fa fa-exclamation-triangle knowledge-icon"></i>
                <h3>故障信息管理</h3>
                <p>管理电机故障记录、维修措施和统计数据</p>
            </div>
        </div>
    `;
    
    // 添加样式
    const style = document.createElement('style');
    style.textContent = `
        .knowledge-menu {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-top: 20px;
        }
        .knowledge-menu-item {
            flex: 1 1 300px;
            background-color: #fff;
            border-radius: 8px;
            padding: 25px;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            text-align: center;
        }
        .knowledge-menu-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .knowledge-icon {
            font-size: 40px;
            margin-bottom: 15px;
            color: #1890ff;
        }
        .knowledge-menu-item h3 {
            margin: 0 0 10px 0;
            font-size: 18px;
            color: #333;
        }
        .knowledge-menu-item p {
            margin: 0;
            color: #666;
        }
    `;
    document.head.appendChild(style);
    
    // 更新内容区域
    mainContent.innerHTML = html;
}

/**
 * 加载电机向量知识库内容
 * @param {string} contentType - 内容类型 (basic|entity|failure)
 */
function loadKnowledgeContent(contentType) {
    try {
        // 根据内容类型加载对应功能
        switch (contentType) {
            case 'basic':
                if (typeof loadKnowledgeBasicList === 'function') {
                    loadKnowledgeBasicList();
                } else {
                    showMessage('电机基础信息模块未加载，请在index.html中添加对应的JS文件', 'warn');
                }
                break;
            case 'entity':
                if (typeof loadKnowledgeEntityList === 'function') {
                    loadKnowledgeEntityList();
                } else {
                    showMessage('知识图谱实体模块未加载，请在index.html中添加对应的JS文件', 'warn');
                }
                break;
            case 'failure':
                if (typeof loadKnowledgeFailureList === 'function') {
                    loadKnowledgeFailureList();
                } else {
                    showMessage('电机故障信息模块未加载，请在index.html中添加对应的JS文件', 'warn');
                }
                break;
            case 'operation':
                if (typeof loadKnowledgeOperationList === 'function') {
                    loadKnowledgeOperationList();
                } else {
                    showMessage('电机运行监测数据模块未加载，请在index.html中添加对应的JS文件', 'warn');
                }
                break;
            case 'relation':
                if (typeof loadKnowledgeRelationList === 'function') {
                    loadKnowledgeRelationList();
                } else {
                    showMessage('实体关系网络模块未加载，请在index.html中添加对应的JS文件', 'warn');
                }
                break;
            case 'aap_data':
                if (typeof loadAapDataList === 'function') {
                    loadAapDataList();
                } else {
                    showMessage('电机数据表模块未加载', 'error');
                }
                break;
            case 'aap_data_table':
                if (typeof loadAapDataList === 'function') {
                    loadAapDataList();
                } else {
                    showMessage('电机数据表模块未加载', 'error');
                }
                break;
            case 'aap_input':
                if (typeof loadAapInputList === 'function') {
                    loadAapInputList();
                } else {
                    showMessage('工况特定输入参数表模块未加载', 'error');
                }
                break;
            case 'aap_modelinfo':
                if (typeof loadAapModelInfoList === 'function') {
                    loadAapModelInfoList();
                } else {
                    showMessage('模型融合配置表模块未加载', 'error');
                }
                break;
            case 'aap_motorkn':
                if (typeof loadAapMotorKnList === 'function') {
                    loadAapMotorKnList();
                } else {
                    showMessage('电机知识表模块未加载', 'error');
                }
                break;
            case 'am_aap_output':
                if (typeof loadAapOutputList === 'function') {
                    loadAapOutputList();
                } else {
                    showMessage('工况特定输出参数表模块未加载', 'error');
                }
                break;
            default:
                showMessage('未知的内容类型: ' + contentType, 'error');
        }
    } catch (error) {
        console.error('加载内容失败:', error);
        showMessage('加载内容失败: ' + error.message, 'error');
    }
}

// 主函数暴露到全局用于初始化JS调用
window.loadContent = loadContent;

/**
 * 删除FMEAFMES
 * @param {number} id - 记录ID
 */
function deleteFMEAFMES(id) {
    if (!confirm('确定要删除该记录吗？')) {
        return;
    }
    fetch(`${API_BASE}/fmeafmes/${id}`, {
        method: 'DELETE',
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => { throw new Error(text); });
        }
        showMessage('删除成功!', 'success');
        loadFMEAFMES();
    })
    .catch(error => {
        console.error('删除失败:', error);
        showMessage('删除失败: ' + error.message, 'error');
    });
}

/**
 * 编辑FMEAFMES
 * @param {number} id - 记录ID
 */
function editFMEAFMES(id) {
    // 发起请求获取详情
    fetch(`${API_BASE}/fmeafmes/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            showFMEAFMESForm(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            showMessage('获取详情失败: ' + error.message, 'error');
        });
}

function renderReliabilityMetrics(metrics) {
    const reliabilityContainer = document.getElementById('reliability-container');
    if (!reliabilityContainer) return;
    
    let html = '<div class="reliability-metrics-content">';
    
    // 空停率指标
    if (metrics.airShutdownRate !== null && metrics.airShutdownRate !== undefined) {
        html += `
            <div class="detail-group">
                <label>千小时空停率:</label>
                <div>${metrics.airShutdownRate.toFixed(2) + ' ‰'}</div>
            </div>
        `;
    }
    
    // 故障率指标
    if (metrics.faultRate !== null && metrics.faultRate !== undefined) {
        html += `
            <div class="detail-group">
                <label>千小时故障率:</label>
                <div>${metrics.faultRate.toFixed(2) + ' ‰'}</div>
            </div>
        `;
    }
    
    // 发动机拆换率指标
    if (metrics.engineReplacementRate !== null && metrics.engineReplacementRate !== undefined) {
        html += `
            <div class="detail-group">
                <label>发动机拆换率:</label>
                <div>${metrics.engineReplacementRate.toFixed(2) + ' 次/千小时'}</div>
            </div>
        `;
    }
    
    // MTBF指标
    if (metrics.mtbf !== null && metrics.mtbf !== undefined) {
        html += `
            <div class="detail-group">
                <label>平均故障间隔时间(MTBF):</label>
                <div>${metrics.mtbf.toFixed(2) + ' 千小时/次'}</div>
            </div>
        `;
    }
    
    // 可靠度指标
    if (metrics.reliability !== null && metrics.reliability !== undefined) {
        html += `
            <div class="detail-group">
                <label>可靠度:</label>
                <div>${(metrics.reliability * 100).toFixed(2) + '%'}</div>
            </div>
        `;
    }
    
    // 维修频率指标
    if (metrics.maintenanceFrequency !== null && metrics.maintenanceFrequency !== undefined) {
        html += `
            <div class="detail-group">
                <label>维修频率:</label>
                <div>${metrics.maintenanceFrequency.toFixed(2) + ' 次/千小时'}</div>
            </div>
        `;
    }
    
    // 使用困难报告频率指标
    if (metrics.difficultyReportRate !== null && metrics.difficultyReportRate !== undefined) {
        html += `
            <div class="detail-group">
                <label>使用困难报告频率:</label>
                <div>${metrics.difficultyReportRate.toFixed(2) + ' 次/千小时'}</div>
            </div>
        `;
    }
    
    html += '</div>';
    
    reliabilityContainer.innerHTML = html;
}